package com.craftplay.controller;

import com.alibaba.fastjson.JSONObject;
import com.craftplay.common.PageBean;
import com.craftplay.common.ServerResponse;
import com.craftplay.dao.ClassOrderMapper;
import com.craftplay.dao.ClassTypeMapper;
import com.craftplay.dao.PayRedPackageMapper;
import com.craftplay.interceptor.Access;
import com.craftplay.model.*;
import com.craftplay.service.*;
import com.craftplay.util.DateUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 页面控制
 *
 * @author Tom
 * @time 2018/10/8
 */
@Controller
@RequestMapping("/play/page")
public class PageController {
    @Autowired
    PageService pageService;
    @Autowired
    UserService userService;
    @Autowired
    MomentService momentService;
    @Autowired
    CommentService commentService;
    @Autowired
    private ClassTypeMapper classTypeMapper;

    @Autowired
    private ClassOrderMapper classOrderMapper;

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PayRedPackageMapper payRedPackageMapper;

    /**
     * 登录页面
     *
     * @param map
     * @return
     */
    @GetMapping(value = "/login")
    public String login(HashMap<String, Object> map) {
        return "/login";
    }

    /**
     * 登录
     *
     * @param userName
     * @param password
     * @return
     */
    @PostMapping(value = "/login")
    @ResponseBody
    public ServerResponse<String> login(HttpServletRequest request, @RequestParam("userName") String userName, @RequestParam("password") String password) {
        List<AdminUser> adminUsers = pageService.adminUserSelectByUserName(userName);
        if (adminUsers.size() == 0) {
            return ServerResponse.createByErrorMessage("用户名或密码错误");
        } else {
            if (adminUsers.get(0).getPassword().equals(password)) {
                //创建凭证
                HttpSession session = request.getSession();
                //一个小时过期
                session.setMaxInactiveInterval(60 * 60);
                session.setAttribute("loginTime", new Date().getTime());

                return ServerResponse.createBySuccessMessage("登录成功");
            }
            return ServerResponse.createByErrorMessage("用户名或密码错误");
        }

    }

    /**
     * 页面跳转
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/*")
    @Access(authorities = {"login"})
    public String index(HttpServletRequest request) {
        String servletPath = request.getServletPath().replace("/play/page", "");
        return servletPath;
    }


    /**
     * 获取用户表信息
     *
     * @return
     */
    @GetMapping(value = "/getUserList")
    @Access(authorities = {"login"})
    @ResponseBody
    public PageBean<User> getUserList(User user, int page, int limit) {
        PageHelper.startPage(page, limit);
        List<User> users = userService.selectAllUserByColumn(user);
        return new PageBean<>(users);
    }

    /**
     * 更新用户表信息
     *
     * @return
     */
    @PostMapping(value = "/updateUser")
    @Access(authorities = {"login"})
    @ResponseBody
    public ServerResponse<String> updateUser(User user) {
        int updateUserInfo = userService.updateUserInfo(user.getFeature(), user.getTel(), user.getOpenId(), user.getNickname(), user.getUserType());
        if (updateUserInfo > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        } else {
            return ServerResponse.createByErrorMessage("更新失败！");
        }
    }


    /**
     * 获取用户表信息
     *
     * @return
     */
    @GetMapping(value = "/getUnitList")
    @Access(authorities = {"login"})
    @ResponseBody
    public PageBean<Unit> getUnitList(Unit unit, int page, int limit, String order) {
        PageHelper.startPage(page, limit, order);
        List<Unit> unitList = momentService.getUnitList(unit);
        return new PageBean<>(unitList);
    }


    /**
     * 更新活动信息
     *
     * @return
     */
    @PostMapping(value = "/updateUnit")
    @Access(authorities = {"login"})
    @ResponseBody
    public ServerResponse<String> updateUnit(Unit unit) {

        int updateUserInfo = momentService.updateByPageMoment(unit);
        if (updateUserInfo > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        } else {
            return ServerResponse.createByErrorMessage("更新失败！");
        }
    }


    /**
     * 删除活动信息
     *
     * @return
     */
    @PostMapping(value = "/delUnit")
    @Access(authorities = {"login"})
    @ResponseBody
    public ServerResponse<String> delUnit(@RequestParam int unitId) {
        int updateUserInfo = momentService.delUnit(unitId);
        if (updateUserInfo > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        } else {
            return ServerResponse.createByErrorMessage("更新失败！");
        }
    }


    /**
     * 获取微信发送信息
     *
     * @return
     */
    @GetMapping(value = "/getContentList")
    @Access(authorities = {"login"})
    @ResponseBody
    public PageBean<Content> getWeixinList(Content content, int page, int limit) {
        PageHelper.startPage(page, limit);
        List<Content> users = pageService.getContentList(content);
        return new PageBean<>(users);
    }


    /**
     * 更新微信回复信息
     *
     * @return
     */
    @PostMapping(value = "/updateContent")
    @Access(authorities = {"login"})
    @ResponseBody
    public ServerResponse<String> updateContent(Content content) {
        int updateUserInfo = pageService.updateContent(content);
        if (updateUserInfo > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        } else {
            return ServerResponse.createByErrorMessage("更新失败！");
        }
    }

    /**
     * 获取用户表信息
     *
     * @return
     */
    @GetMapping(value = "/getCommentList")
    @Access(authorities = {"login"})
    @ResponseBody
    public PageBean<Comment> getCommentList(Comment comment, int page, int limit, String order) {
        PageHelper.startPage(page, limit, order);
        List<Comment> unitList = commentService.getCommentList(comment);
        return new PageBean<>(unitList);
    }


    /**
     * 获取课程表信息
     *
     * @return
     */
    @GetMapping(value = "/getClassStatus")
    @Access(authorities = {"login"})
    @ResponseBody
    public PageBean<OrderDTO> getClassStatus(OrderDTO orderDTO, int page, int limit, String order) {
        Page<Object> objects = PageHelper.startPage(page, limit, order);
        List<ClassOrder> classOrders = classOrderMapper.selectAllClass();
        List<OrderDTO> orderDTOS = new ArrayList<>();
        PageBean<OrderDTO> outDTO = new PageBean<>(orderDTOS);
        classOrders.stream().forEach(t -> {
            User user = userService.selectUserById(t.getUserId());
            OrderDTO dto = new OrderDTO();
            dto.setId(t.getId());
            dto.setUserName(user.getNickname());
            dto.setHeadUrl(user.getHeadUrl());
            dto.setUserId(user.getUserId());
            dto.setTel(user.getTel());
            List<ClassType> classTypes = classTypeMapper.selectByClassTree(t.getClassType());
            for (ClassType classType : classTypes) {
                if (classType.getClassTreeType() == t.getClassTreeType()) {
                    dto.setClassTreeDesc(classType.getClassTreeDesc());
                    dto.setClassDesc(classType.getClassDesc());
                }
            }
            dto.setMoney((double) t.getMoney() / 100);
            dto.setCreateTime(t.getCreateTime());
            dto.setMessage(t.getMessage());
            dto.setClassStatus(t.getClassStatus());
            dto.setStatus(t.getStatus());

//            //获取付款信息
//            List<PayRedPackage> payRedPackages = payRedPackageMapper.selectByUnit(t.getUnitId());
//            if (payRedPackages != null && payRedPackages.size() > 0) {
//                for (PayRedPackage payRedPackage : payRedPackages) {
//                    Integer payType = payRedPackage.getPayType();
//                    String payTypeName = PayTypeEnum.getPayTypeName(payType);
//                    String payType1 = dto.getPayType();
//                    payType1 += DateUtils.dateToLongString(payRedPackage.getPaytime()) + "已付" + payTypeName + ":" + payRedPackage.getMoney();
//                    dto.setPayType(payType1);
//                }
//            }
//
            Unit unit = momentService.oneMomentDetail(t.getUnitId());
            if (unit != null) {

                User teacher = userService.selectUserById(unit.getUserId());
                dto.setTeacher(teacher.getNickname());
                dto.setTeacherTel(teacher.getTel());

                orderDTOS.add(dto);
            } else {
                System.out.println(JSONObject.toJSONString(unit));
            }
        });
        outDTO.setList(orderDTOS);
        outDTO.setPageNum(page);
        outDTO.setPageSize(limit);
        outDTO.setTotal(objects.getTotal());
        return outDTO;
    }

    /**
     * 课程退款
     *
     * @return
     */
    @PostMapping(value = "/refundClass")
    @Access(authorities = {"login"})
    @ResponseBody
    @Transactional
    public ServerResponse<String> refundClass(OrderDTO orderDTO) {
        ClassOrder classOrder = classOrderMapper.selectById(orderDTO.getId());
        if (classOrder == null) {
            return ServerResponse.createByErrorMessage("课程获取失败！");
        }
        if (classOrder.getClassStatus() == -2) {
            return ServerResponse.createByErrorMessage("课程已经退款");
        }
        if (classOrder.getStatus() == 2) {
            return ServerResponse.createByErrorMessage("已支付尾款不能退款");
        }

        weixinService.refundClass(classOrder);
        classOrder.setClassStatus(-2);
        int i = classOrderMapper.updateClassStatus(classOrder);
        if (i > 0) {
            return ServerResponse.createBySuccessMessage("课程退款成功");
        }
        return ServerResponse.createByErrorMessage("课程退款失败！");


    }

    /**
     * 课程尾款
     *
     * @return
     */
    @PostMapping(value = "/sendEndClass")
    @Access(authorities = {"login"})
    @ResponseBody
    @Transactional
    public ServerResponse<String> sendEndClass(OrderDTO orderDTO) throws Exception {
        ClassOrder classOrder = classOrderMapper.selectById(orderDTO.getId());
        if (classOrder == null) {
            return ServerResponse.createByErrorMessage("课程获取失败！");
        }
        if (classOrder.getClassStatus() == -2) {
            return ServerResponse.createByErrorMessage("已退款不能支付尾款！");
        }
        if (classOrder.getClassStatus() <= 3) {
            return ServerResponse.createByErrorMessage("课程未上完3节课不能支付！");
        }
        if (classOrder.getStatus() != null && classOrder.getStatus() == 2) {
            return ServerResponse.createByErrorMessage("已结支付尾款！");
        }
        classOrder.setStatus(2);
        classOrderMapper.updateStatus(classOrder);
        weixinService.sendEndClass(classOrder);
        return ServerResponse.createBySuccessMessage("课程尾款成功");

    }


}
